using System;
using System.Linq;
using Soft1ApiDemo.Domain;
using Soft1ApiDemo.Domain.Repository;
using Soft1ApiDemo.Infrastructure.Db;
using Microsoft.EntityFrameworkCore;

namespace Soft1ApiDemo.Infrastructure.Repository
{
    public class RepositoryBase<T>:IRepository<T> where T:BaseEntity
    {
        private readonly Soft1ApiDemoDbContext _db;
        private readonly DbSet<T> _table;
        public RepositoryBase(Soft1ApiDemoDbContext db)
        {
            _db=db;
            _table=_db.Set<T>();
        }
        public IQueryable<T> Table
        {
            get
            {
                return _table.AsNoTracking();
            }
        }
        public T GetById(Guid id)
        {
            var entity=_db.Set<T>().AsQueryable().Where(x=>x.Id==id).FirstOrDefault();
            return entity;
        }
        public T Add(T entity)
        {
            entity.IsActived=true;
            entity.IsDeleted=false;
            entity.CreatedAt=DateTime.Now;
            entity.UpdatedAt=DateTime.Now;
            entity.DisplayOrder=0;
            _table.Add(entity);
            _db.SaveChanges();
            return entity;
        }
        public void Update(T entity)
        {
            entity.UpdatedAt=DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }
        public void Delete(Guid id)
        {
            var entity=this.GetById(id);
            if(entity!=null)
            {
                entity.IsDeleted=true;
                _table.Update(entity);
                _db.SaveChanges();
            }
        }
    }
}